﻿

//添加出库单
layui.use(function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var util = layui.util;
    //获取跳转过来的id
    var urlParams = new URLSearchParams(window.location.search);
 
    var id = urlParams.get('ID');

    //选中产品的值
    var selected = [];
    var totalPrice = 0;


    var token = localStorage.getItem("token");

  





    //新增产品显示
    util.on('lay-on', {
        "test-page": function () {
            var index = layer.open({
                type: 1,
                title: '新增出库产品单',
                area: ['1100px', '500px'], // 宽高
                content: '<form class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px" >产品编码:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="productsCode" placeholder="产品编码" style="width:200px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px">产品名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="B" placeholder="产品名称" id="productsName" style="width:200px;" lay- affix="clear" class= "layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchBtnPro" > 查询</button>' +
                    '</div> ' +
                    '</form>' +
                    '<table class= "layui-table" id="Produrement-Id" lay-filter="test">' +
                    '</table>' +
                    '<button type="button" id="demo-login" class="layui-btn layui-bg-blue style=text-align:center">提交</button>'
            });
            form.render();

            GetProductList(1)
            //查询
            $("#searchBtnPro").on('click', function () {
                var ClientCode = $("#ClientCode").val();
                var ClientName = $("#ClientName").val();
                GetProductList({
                    ClientCode: ClientCode,
                    ClientName: ClientName,
                    Landline: '',
                    PageIndex: 1,
                    PageSize: 5
                });
            })

            var ids = [];
            var check = [];

            //获取复选框的值
            table.on('checkbox(test)', function (obj) {
                var checkeddata = obj.data; // 获取所有选中的行数据
                if (obj.checked) {
                    ids.push(checkeddata.storehouseId);
                    check.push(checkeddata);
                } else {
                    var indexToRemove = ids.indexOf(checkeddata.storehouseId);
                    if (indexToRemove !== -1) {
                        ids.splice(indexToRemove, 1);  // 从 ids 数组中移除
                        check.splice(indexToRemove, 1); // 从 check 数组中移除
                    }
                }
                console.log(ids);
                console.log(check);
            })

            //选中产品显示
            $('#demo-login').click(function () {
                layer.close(index);
                table.render({
                    elem: "#table-demo",
                    width: 1300,
                    css: [
                        // 设置单元格样式
                        // 取消默认的溢出隐藏，并设置适当高度
                        '.layui-table-cell{height: 50px; line-height: 40px;}',
                        '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                        '.layui-table-cell select{height: 36px; padding: 0 5px;}',
                    ].join(''),
                    cols: [[
                        { type: 'checkbox' },
                        { field: 'productsName', title: '产品名称', width: 150 },
                        { field: 'productsCode', title: '产品编码', width: 150 },
                        { field: 'specs', title: '规格', width: 100 },
                        { field: 'price', title: '单价', width: 150 },
                        { field: 'batch', title: '批次', width: 150, edit: 'text' },
                        { field: 'storehouseId', title: '库位', width: 150, },
                        { field: 'sellProductNum', title: '出库数', width: 150, },
                        {
                            field: 'pricenum', title: '总价', width: 150, edit: 'text', templet: function (d) {
                                if (d.sellProductNum != null && d.price != null) {
                                    return d.sellProductNum * d.price;
                                } else {
                                    return 0;
                                }
                            }
                        },
                     
                    ]],
                    data: check,

                    done: function (res, curr, count) {
                        console.log(res);
                        totalPrice = Number(res.sellProductNum) * Number(res.price);
                        table.on('edit(table-demo)', function (obj) {
                            console.log(obj);
                            var value = obj.value; // 得到修改后的值
                            var data = obj.data; // 得到所在行所有键值
                            console.log(data)
                            var field = obj.field; // 得到字段

                        });

                        //获取复选框的值
                        table.on('checkbox(table-demo)', function (obj) {
                            console.log(obj);
                            //当前选中的行加入到 selected 数组中
                            if (obj.checked) {
                                selected.push(obj.data);
                            }
                            else {
                                // 当前取消选中的行从 selected 数组中移除
                                selected = selected.filter(row => row.productsID !== obj.data.productsID);
                            }
                            console.log(selected)
                        })


                    }
                })
            });

        }
    })

    //产品列表
    function GetProductList(psize) {
        var dto = {
            Token: token,
            pindex: 1,
            psize: 10,
            SalesCode: $("#procurementCode").val() || '',
            ProductsCode: $("#productsCode").val() || '',
            ProductsName: $("#productsName").val() || '',
            ProcureState: $("#procureState").val() || '',
        };
        $.ajax({
            url: '/Sales/GetSales',
            type: "get",
            data: dto,
            success: function (res) {
                var data = JSON.parse(res)
                console.log(data.data.list)
                if (res != null) {
                    // 创建表格实例
                    table.render({
                        elem: '#Produrement-Id',
                        height: 300,
                        cols: [[
                            { type: 'checkbox', fixed: true },
                            { field: 'productsCode', title: '产品编码', width: 150 },
                            { field: 'productsName', title: '产品名称', width: 150 },
                            { field: 'specs', title: '规格', width: 150, sort: true },
                            { field: 'storageUnits', title: '存储单位', width: 150 },
                            { field: 'price', title: '单价', width: 100 },


                        ]],
                        data: data.data.list,
                        page: true,
                        limit: 10,
                        limits: [10, 20, 30],

                    });
                }
            }
        })
    }







    //双击编号显示弹框

    var inputElement = document.getElementById("ClientCode");
    // 在这里可以使用 supplierIdValue 变量

    var Clicheck = [];
    inputElement.addEventListener('click', function (event) {

        if (event.detail == 2) {
            var index = layer.open({
                type: 1,
                title: '选择客户',
                area: ['900px', '500px'],
                content: '<table class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" >客户编号:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="Code"    style="width:100px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label">客户名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="ClientName"   style="width:100px;"  class= "layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchCliBtn" style="margin-left: 50px;">查询</button>' +
                    '</div> ' +
                    '</table>' +
                    '<table class= "layui-table" id="ClientTable" >' +
                    '</table>' +
                    '<button type="button" id="demo-gysshows" class="layui-btn layui-bg-blue" >提交</button>',
            });
            form.render();

            //调用客户列表
            GetClientList(1);

            //查询
            //$(document).ready(function () {
            $("#searchCliBtn").on('click', function () {

                var ClientCode = $("#Code").val();
                var ClientName = $("#ClientName").val();
                console.log(ClientCode);
                GetClientList({
                    ClientCode: ClientCode,
                    ClientName: ClientName,
                    PageIndex: 1,
                    PageSize: 10
                });
            });
            //});

            //获取复选框的值
            table.on('checkbox(ClientTable)', function (obj) {
                console.log(obj);
                // 当前选中的行加入到 selectedRows 数组中
                Clicheck.push(obj.data);
                console.log(Clicheck)
            })
            //form.render();


            //显示选中的供应商信息(点击提交)
            $("#demo-gysshows").on('click', function () {
                //关闭弹出层
                layer.close(index);
                $("#ClientCode").val(Clicheck[0].clientCode);
                $("#ClientName").val(Clicheck[0].clientName);
                CliDetail()

            })



        } else {  //单击
            inputElement.readOnly = false;
            inputElement.focus();
        }
    });

    //失去焦点恢复只读
    inputElement.addEventListener('blur', function () {
        inputElement.readOnly = true;
    });


    //客户信息
    function GetClientList({ ClientCode, ClientName, PageIndex, PageSize }) {
        let dtos = {
            ClientCode: ClientCode,
            ClientName: ClientName,
            PageIndex: 1,
            PageSize: 50,
            Token: token
        };

        $.ajax({
            url: '/Client/GetClientShow',
            type: "get",
            data: dtos,
            success: function (res) {
                var data = JSON.parse(res)
                console.log(data.data)
                //渲染表格
                table.render({
                    elem: '#ClientTable',
                    cols: [[
                        { type: 'checkbox', fixed: 'left' }, // 启用多选框
                        { field: 'clientCode', title: '客户编号' },
                        { field: 'clientName', title: '客户名称' },
                        { field: 'landline', title: '电话' },
                        { field: 'cfax', title: '传真' },
                        { field: 'mailbox', title: 'Email' },
                        { field: 'ccontact', title: '联系人' },
                        { field: 'caddress', title: '地址' },
                    ]],
                    data: data.data.list,//数据源
                    page: true,
                    limit: 10,
                    limits: [10, 20, 30],
                    curr: 1,
                    total: data.data.lcount,  // 总记录数
                    loading: true, // 启用加载状态

                });
            }
        })
    }

    //显示客户信息
    function CliDetail() {
        console.log(Clicheck);
        var obj = {
            Token: token,
            ClientId: Clicheck.clientId,
        }
        console.log(obj);
        $.ajax({
            url: '/Client/GetClientFt',
            type: "get",
            data: obj,
            success: function (res) {
                console.log(res);
                var data = JSON.parse(res)
                console.log(data.data)
                // 为 select 渲染选项
                var selectHtml = '<option value="">请选择</option>';
                Clicheck.forEach(function (item) {
                    console.log(item);
                    selectHtml += `<option value=${item.ccontact}>${item.ccontact}</option>`;
                });

                // 更新 select 元素的 HTML
                $('#Ccontact').html(selectHtml);
                // 渲染 select 元素
                form.render('select');
                $("#VendorPhone").val(Clicheck[0].landline)
            }




        })
    }


    //反填

        var obj = {
            OutShipId: id,
            Token: token
        }

        $.ajax({
            url: '/OutBound/OutShipDetail',
            type: 'get',
            data: obj,
            success: function (res) {
                var datas = JSON.parse(res);
                console.log(datas);
                table.render({
                    elem: "#table-demo",
                    width: 1300,
                    css: [
                        // 设置单元格样式
                        // 取消默认的溢出隐藏，并设置适当高度
                        '.layui-table-cell{height: 50px; line-height: 40px;}',
                        '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                        '.layui-table-cell select{height: 36px; padding: 0 5px;}',
                    ].join(''),
                    cols: [[
                        { type: 'checkbox' },
                        { field: 'productsName', title: '产品名称', width: 150 },
                        { field: 'productsCode', title: '产品编码', width: 150 },
                        { field: 'specs', title: '规格', width: 100 },
                        { field: 'outPrice', title: '单价', width: 150 },
                        { field: 'batch', title: '批次', width: 150, edit: 'text' },
                        { field: 'binlocation', title: '库位', width: 150, },
                        { field: 'outProuductNum', title: '出库数', width: 150, },
                        {
                            field: '', title: '总价', width: 150, edit: 'text', templet: function (d) {
                                if (d.outProuductNum != null && d.outPrice != null) {
                                    return d.outProuductNum * d.outPrice;
                                } else {
                                    return 0;
                                }
                            }
                        },

                    ]],
                    data: datas.data,
                    page: true,
                    limit: 10,
                    limits: [10, 20, 30],

                    done: function (res, curr, count) {
                        table.on('edit(table-demo)', function (obj) {
                            console.log(obj);
                            var value = obj.value; // 得到修改后的值
                            var data = obj.data; // 得到所在行所有键值
                            console.log(data)
                            var field = obj.field; // 得到字段

                        });

                        //获取复选框的值
                        table.on('checkbox(table-demo)', function (obj) {
                            console.log(obj);
                            //当前选中的行加入到 selected 数组中
                            if (obj.checked) {
                                selected.push(obj.data);
                            }
                            else {
                                // 当前取消选中的行从 selected 数组中移除
                                selected = selected.filter(row => row.productsID !== obj.data.productsID);
                            }
                            console.log(selected)
                        })
                    }
                });

                //反填出库
                $(datas.data).each(function () {
                    console.log(this);
                    var date = new Date(this.markTime);
                    var year = date.getFullYear();
                    var month = (date.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                    var day = date.getDate().toString().padStart(2, '0');  // 补充两位数字
                    var formattedDate = `${year}-${month}-${day}`;

                    $("#outShipCode").val(this.outShipCode);
                    $("#outShipType").val(this.outShipType);
                    $("#orderNumber").val(this.orderNumber);
                    $("#ClientCode").val(this.clientCode);
                    $("#Ccontact").val(this.ccontact);
                    form.render('select');
                    $("#ClientName").val(this.clientName);
                    $("#VendorPhone").val(this.vendorPhone);

                    $("#makePerson").val(this.makePerson);
                    $("#markTime").val(formattedDate);
                    $("#oRremark").val(this.oRremark);
                    layui.form.render('select'); 
                })




            }

        })
    



    //添加提交
    $("#submit").click(function () {

        var code = Math.floor(Math.random() * 1000000) + 100000;
        code = code.toString();
        var select = selected.map(function (item) {
            console.log(item);

            return {
                "productsID": item.productsID,
                "batch": item.batch,
                "outPrice": item.price,
                "outProuductNum": item.sellProductNum,
            }
        });
        var model = {
            "outShipCode": code,
            "outShipType": $("#outShipType").val(),
            "orderNumber": $("#orderNumber").val(),
            "clientId": Clicheck[0].clientId,
            "clientCode": Clicheck[0].clientCode,
            "clientName": Clicheck[0].clientName,
            "ccontact": $("#Ccontact").val(),
            "vendorPhone": Clicheck[0].landline,
            "makePerson": $("#makePerson").val(),
            "markTime": $("#markTime").val(),
            "oRremark": $("#oRremark").val(),
            salesId: selected[0].salesId,
            OPlist: select,
            Token: token
        }
        console.log(model);

        $.ajax({
            url: '/OutBound/OutShipUPT',
            type: "post",
            data: model,
            success: function (res) {

                var data = JSON.parse(res)
                console.log(data);
                if (data.data > 0) {
                    layer.msg("修改成功", { icon: 1, time: 1000 }, function () {
                        location.href = "/OutBound/GetOutBoundList";
                    });
                } if (data.data == -1) {
                    layer.msg("产品库存不足", { icon: 2, time: 1000 }, function () {
                        return false;
                    });
                } if (data.data == -2) {
                    layer.msg("与销售数量不符", { icon: 2, time: 1000 }, function () {
                        return false;
                    });
                }
                return false;
            }

        })

    })




})
